package com.example.scanlogin;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.client.j2se.MatrixToImageWriter;
/**
 * @description: 根据文字生成图片/Base64编码
 * @author: Leon
 * @date: 2025/1/10  18:48
 */
@Slf4j
public class TextPictureConverse {
 
    public static String generateQRCodeBase64(String text, int width, int height) {
        try {
            // 设置二维码参数
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 设置字符编码
            // 生成二维码矩阵
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            // 将二维码写入字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "PNG", outputStream);
            // 将字节数组转换为 Base64 字符串
            byte[] qrCodeBytes = outputStream.toByteArray();
            return Base64.getEncoder().encodeToString(qrCodeBytes);
        } catch (WriterException | IOException e) {
            log.info("生成登录二维码失败！{}", e.getMessage());
            throw new RuntimeException("生成二维码失败！", e);
        }
    }

    public static void main(String[] args) {
        // 要编码的文本,
        String data = "token=63F5DEA1E90CCB2C8A48A72149824812B5A0E26BFA806F03300332D4CE74B47C5993D8DF9C523D0A32B2418EEA19A67CAB4B2158107AD8D62EA5A25FCDB9E5C3";
        // 生成的二维码图片文件路径
        int width = 600; // 二维码宽度
        int height = 600; // 二维码高度
        String base64QRCode = generateQRCodeBase64(data, width, height);
        System.out.println(base64QRCode);
    }
}

